package controller;

import Dao.UserDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class UserFindServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDao dao = new UserDao();
/*
        // 索要当前用户在服务端HttpSession
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect("/myWeb/login_error.html");
            return;
        }

 */

        // 提供服务
        response.setContentType("text/html;charset=utf-8");
        // 1、调用DAO将查询命令推送到数据库服务器上，得到所有用户信息[List]
        List<User> users = dao.findAll();
        // 2、【调用响应对象】将用户信息结合<table>标签命令以二进制形式写入到响应体
        PrintWriter out = response.getWriter();
        StringBuilder sb = new StringBuilder();
        sb.append("<center><table align='center' border='2px'>");
        sb.append("<tr align='center'><th>userId</th><th>userName</th><th>password</th>" +
                "<th>sex</th><th>email</th><th>操作</th></tr>");
        for (User user : users) {
            int userId = user.getUserId();
            String userName = user.getUserName();
            String password = user.getPassword();
            String sex = user.getSex();
            String email = user.getEmail();
            sb.append("<tr><td>");
            sb.append(userId + "</td>");
            sb.append("<td>");
            sb.append(userName + "</td>");
            sb.append("<td>");
            sb.append(password + "</td>");
            sb.append("<td>");
            sb.append(sex + "</td>");
            sb.append("<td>");
            sb.append(email + "</td>");
            sb.append("<td><a href='/myWeb/user/delete?userId=" + userId +"'>");
            sb.append("删除</a></td></tr>");
        }
        sb.append("</table></center>");
        out.print(sb.toString());
    }
}
